package com.neurotech.pcc.ui

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.DialogInterface
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.*
import androidx.navigation.fragment.NavHostFragment
import com.neurotech.pcc.R
import com.neurotech.pcc.dummy.RemoteModel
import com.neurotech.pcc.dummy.RemotesDatabase
import com.neurotech.pcc.other.NetworkUtils
import com.neurotech.pcc.other.RemoteClient
import com.neurotech.pcc.other.ThreadPool
import com.neurotech.pcc.other.liteStatusBarIcon
import com.neurotech.pcc.ui.adapter.MainItemAdapter
import com.neurotech.pcc.vm.RemotesRepository
import com.neurotech.pcc.vm.RemotesRepositoryFactory
import com.neurotech.pcc.vm.RemotesViewModel
import com.neurotech.pcc.widgets.SwipeItemLayout
import kotlinx.android.synthetic.main.fragment_main.*

/**
 * A Main Fragment class.
 * @author shenhua
 */
class MainFragment : Fragment() {

    private lateinit var remotesViewModel: RemotesViewModel
    private lateinit var adapter: MainItemAdapter
    private var remoteModel: RemoteModel? = null
    private var remoteModels: List<RemoteModel>? = null

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        val factory = RemotesRepositoryFactory(RemotesRepository.dao(RemotesDatabase.getInstance(context
                ?: activity!!).remoteDao()))
        remotesViewModel = ViewModelProviders.of(this, factory)[RemotesViewModel::class.java]

        adapter = MainItemAdapter()
        remotesViewModel.getRemotes().observe(viewLifecycleOwner, Observer {
            if (it == null || it.isEmpty()) {
                emptyView.visibility = View.VISIBLE
                groupCl.visibility = View.GONE
            } else {
                emptyView.visibility = View.GONE
                groupCl.visibility = View.VISIBLE
            }
            remoteModels = it
            adapter.submitList(it)
        })

        setHasOptionsMenu(true)
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        swipeRefreshLayout.setOnRefreshListener {
            swipeRefreshLayout.postDelayed({
                if (activity != null && !activity!!.isFinishing) {
                    adapter.notifyDataSetChanged()
                    swipeRefreshLayout?.isRefreshing = false
                }
            }, 1000)
        }

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = adapter
        recyclerView.addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(context))

        adapter.deleteListener = object : MainItemAdapter.DeleteListener {
            override fun onDelete(remoteModel: RemoteModel) {
                remotesViewModel.delete(remoteModel)
                Snackbar.make(recyclerView, R.string.text_deleted, Snackbar.LENGTH_SHORT).show()
            }
        }
        adapter.clickListener = object : MainItemAdapter.ClickListener {
            override fun onClick(view: View, remoteModel: RemoteModel?) {
                this@MainFragment.remoteModel = remoteModel
                if (remoteModel == null
                        || TextUtils.isEmpty(remoteModel.host)
                        || TextUtils.isEmpty(remoteModel.mac)
                        || TextUtils.isEmpty(remoteModel.port)
                ) {
                    return
                }
                registerForContextMenu(view)
                view.showContextMenu()
            }
        }
        // 全部关机
        btn_shutdown_all.setOnClickListener {
            AlertDialog.Builder(it.context).apply {
                setMessage(getString(R.string.info_shutdown_all_ask))
                setPositiveButton(R.string.confirm) { dialog, which ->
                    /**
                     * This method will be invoked when a button in the dialog is clicked.
                     *
                     * @param dialog the dialog that received the click
                     * @param which the button that was clicked (ex.
                     * [DialogInterface.BUTTON_POSITIVE]) or the position
                     * of the item clicked
                     */
                    for (remoteModel in remoteModels!!) {
                        val remoteClient = RemoteClient(context, remoteModel)
                        remoteClient.shutdown1()
                    }
                }
                setNegativeButton(R.string.text_cancel, null)
                create().show()
            }
        }
        // 全部开机
        btn_wakeup_all.setOnClickListener {
            for (remoteModel in remoteModels!!) {
                NetworkUtils.wake(remoteModel.mac!!, remoteModel.port!!)
            }
        }
    }

    override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
        super.onCreateContextMenu(menu, v, menuInfo)
        menu?.add(0, 1, 0, R.string.text_wakeup)
        menu?.add(0, 2, 0, R.string.text_shutdown)
    }

    override fun onContextItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == 1) {
            NetworkUtils.wake(remoteModel?.mac!!, remoteModel?.port!!)
        }
        if (item?.itemId == 2) {
            ThreadPool.get().thread().execute {
                val remoteClient = RemoteClient(context!!, remoteModel!!)
                remoteClient.shutdown1()
            }
        }
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        inflater?.inflate(R.menu.menu_scan, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_scan) {
            NavHostFragment.findNavController(this).navigate(R.id.action_mainFragment_to_scanFragment)
            adapter.stop()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onResume() {
        super.onResume()
        liteStatusBarIcon(activity?.window?.decorView)
    }

}
